import HttpRequest from "./request";
import { BASE_URL, CODE_TEXT_COLOR, TIME_OUT } from "./config";
import { useUserStore } from "@/store/global";
import { Notification } from "@arco-design/web-vue";
import { IconCloseCircleFill } from "@arco-design/web-vue/es/icon";
import { h } from "vue";
import router from "@/router/index.ts";
const httpRequest = new HttpRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  //@ts-ignore
  interceptors: {
    //请求拦截器配置
    requestInterceptor: (config) => {
      // 携带token的拦截
      const useUser = useUserStore();
      if (!useUser.token) {
        router.push("/login");
      } else {
        config.headers["Authorization"] = "Bearer " + useUser.token;
      }
      return config;
    },
    //请求拦截器捕获错误
    requestInterceptorCatch: (err) => {
      return err;
    },
    //响应拦截器配置
    responseInterceptor: (response) => {
      if (
        response.status === 200 &&
        response.data &&
        response.data.code != 200
      ) {
        Notification.info({
          title: "提示",
          content: response.data.msg,
          icon: () => h(IconCloseCircleFill, { style: { color: "red" } }),
          closable: true,
        });
      }
      return response;
    },
    //响应拦截器捕获配置
    responseInterceptorCatch: (err) => {
      if (err.response) {
        console.log(err);
        
        Notification.error({
          title: "提示",
          content:
            err.response.data.msg || CODE_TEXT_COLOR[err.response.status],
          icon: () => h(IconCloseCircleFill, { style: { color: "red" } }),
          closable: true,
        });
        if (err.response.status === 401) {
          router.push("/login");
        }
      }

      return err;
    },
  },
});
export default httpRequest;
